<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn"%>
<!doctype html>
<html>
<head>
	<title>客户分类</title>

	<script type="text/javascript">
		var pageListUrl = "<c:url value="/customerGroup/list" />";
		var loadByIdUrl = "<c:url value="/customerGroup/load/" />";
		var saveUrl = "<c:url value="/customerGroup/save" />";
		var delByIdUrl = "<c:url value="/customerGroup/del/" />";

		var detailTbodyTemplateID = "detailTbodyTemplate";
		var detailTbodyID = "detailTbody";
		var pageToolID = "pageTool";

		var editTemplateID = "edit-template";
		var editFormID = "nsForm";
		var searchFormID = "searchForm";

		var g_groupId;


		$(function () {
			toPage(1);
		});

		template.helper('separatorValue', function (val) {
			if(val != null && val.length > 0){
				var array = val.split(",");
				var tmp= "";
				$.each(array, function(i, v){
					if(i > 0){
						tmp += "<BR/>";
					}
					tmp += v;
				});
				return tmp;
			}
		});

		function del(id) {
		    var layerIndex = layer.confirm('数据删除后将不可恢复，确定删除？', {
		        icon: 3,
		        title:'提示',
		        btn: ['确认', '取消']
		    }, function () {
		        ns.close(layerIndex);
		        layerIndex = ns.load("正在保存数据.....");
		        $.ajax({
		            type: 'POST',
		            url: delByIdUrl + id,
		            cache: false,
		            data: {
		                id: id
		            },
		            error: function () {
		                ns.error('操作失败');
		            },
		            success: function (data) {
		                ns.close(layerIndex);
		                if (data.success) {
		                    ns.ok('操作成功', function () {
		                        toPage(1);
	                        	toCustomerPage();
	                        	$("#addCustomerToGroupBtn").hide();
	                        	$("#customerDetailBox").text("");
		                    });
		                } else {
		                    ns.error('操作失败：' + data.message);
		                }
		            }
		        });
		    });
		}
	</script>

</head>


<body  class="list-body">


<div class="content">
	<div class="title fix">
		<h3 class="b f14 fl">客户分类</h3>
		<div class="btns fr">
			<%--<button class="green" onclick="add()">新增客户分类</button>--%>
			<%--<button class="orange">返回</button>--%>
		</div>
	</div>

	<div class="main" style="overflow: auto;  ">
		<%--<div style="width:400px;float:left;display: inline-block;">--%>
		<div class="inquiry">
			<form id="searchForm">
				<input type="hidden" name="currentPage" value="1">
				<input type="hidden" name="toolStyle" value="pms">
				<input type="hidden" name="limit" value="10">
				<input type="hidden" name="method" value="toPage">
				<input type="hidden" name="dealerId" value="${dealerNum}">

				<%--<div class="group"><label>活动名称：</label><input type="text" name="name" value=" " /></div>--%>
				<%--<div class="group"><label>活动时间：</label><input type="text" name="name" value=" " /> - <input type="text" name="name" value=" " /></div>--%>
				<%--<div class="group"><label>活动状态：</label><input type="text" name="name" value=" " /></div>--%>
				<%--<div class="btns"><button type="button" class="bottleGreen vm" onclick="toPage(1)">查看</button></div>--%>
			</form>
			<div class="btns " style="width: 100%;">
				<button class="green" onclick="add()">新增</button>
				<c:if test="${null != returnBtnEnabled}">
					<div class="btns" style="position: relative; top: -7px; float: right;">
						<button class="orange" onclick="returnPath('${returnBtnEnabled}','${send}','${remindMonth}')">返回</button>
					</div>
				</c:if>
			</div>
		</div>
		<div class="table">
			<table width="100%" id="groupTable">
				<thead>
				<tr>
					<%--<th width="5%"><input type="checkbox" name="name" value=" " /></th>--%>
					<th width="50">序号</th>
					<th width="">分类名称</th>
					<th width="">最后修改时间</th>
					<th width="100">操作</th>
				</tr>
				</thead>
				<tbody id="detailTbody" class="detailTr"></tbody>
			</table>
		</div>

		<div class="pageTool" id="pageTool"></div>

		<div style="vertical-align: top;overflow:hidden;">
			<div style="height: 44px;vertical-align: middle;line-height: 25px;margin-top: 10px;">
				<div class="btns fl">
					<button class="green " id="addCustomerToGroupBtn" style="display: none;" onclick="addCustomer()">添加客户至分类</button>
				</div>
				<h3 class="b f14 fl"><label class="msg-label orange b" id="customerDetailBox"></label> </h3>
			</div>
			<div class="">
				<form id="searchForm_customer">
					<input type="hidden" name="currentPage" value="1">
					<input type="hidden" name="toolStyle" value="pms">
					<input type="hidden" name="limit" value="10">
					<input type="hidden" name="method" value="toCustomerPage">
					<input type="hidden" name="dealerNum" value="${dealerNum}">
					<input type="hidden" name="customerGroupId" id="customerGroupId" value="">

				</form>

			</div>
			<div class="table ">
				<table width="100%">
					<thead>
					<tr>
						<th width="50">序号</th>
						<th width="120">客户</th>
						<th width="80">手机号码</th>
						<th width="60">车牌号</th>
						<th width="60">车品牌</th>
						<th width="">最近一年到店次数</th>
						<th width="">最近一年消费金额</th>
						<th width="80">上次保养时间</th>
						<th width="">上次保养金额</th>
						<th width="">上次保养里程</th>
						<th width="">上次保养项目</th>
						<th width="50">操作</th>
					</tr>
					</thead>
					<tbody id="detailTbody_customer" class="detailTr"></tbody>
				</table>
			</div>

			<div class="pageTool" id="pageTool_customer"></div>
		</div>
	</div>
</div>
<script id="detailTbodyTemplate" type="text/html">
	{{each items as v i}}
	<tr id="{{v.id}}" onclick="changeGroup('{{v.id}}', '{{v.groupName}}', {{v.isCustom ? 'true':'false'}})">
		<td style="display:none;">{{v.id}}</td>
		<td>{{start + i + 1}}</td>
		<td>{{v.groupName}}</td>
		<td>{{v.lastUpdateDate}}</td>
		<td class="operate_td">
			{{if v.isCustom}}
			<a href='javascript:void(0);' onclick="edit('{{v.id}}')">编辑</a>
			<a href='javascript:void(0);' onclick="del('{{v.id}}','customerGroup')">删除</a>
			{{/if}}
		</td>
	</tr>
	{{/each}}
	{{if items.length == 0}}
	<tr>
		<td colspan="7" class="none-data-tip">没有相关数据</td>
	</tr>
	{{/if}}
</script>


<script id="edit-template" type="text/html">
	<form id="nsForm" method="post" class="form-box">
		<input type="hidden" name="id" value="{{id}}"/>
		<input type="hidden" name="dealerId" value="${dealerNum}"/>

		<div class="box-body">
			<div class="form-group">
				<label>分类名称</label>
				<input name="groupName" placeholder="请输入分类名称..." value="{{groupName}}">
			</div>
		</div>

	</form>

</script>


<script id="detailTbodyTemplate_customer" type="text/html">
	{{each items as v i}}
	<tr id="{{v.id}}" >
		<td>{{start + i + 1}}</td>
		<td>{{v.memberName}}</td>
		<td>{{v.mobilePhone}}</td>
		<td>{{separatorValue v.carPlate}}</td>
		<td>{{separatorValue v.carBrand}}</td>
		<td>{{v.countOfToStore}}</td>
		<td>{{v.moneyOfYear}}</td>
		<td>{{v.lastMaintenanceDate}}</td>
		<td>{{v.lastMaintenanceMoney}}</td>
		<td>{{separatorValue v.lastMaintenanceMileage}}</td>
		<td>{{v.lastMaintenanceItemDisplay}}</td>
		<td class="operate_td">
			<a href='javascript:void(0);' onclick="delCustomer('${dealerNum}', '{{v.customerId}}', '{{v.customerGroupId}}')">删除</a>
		</td>
	</tr>
	{{/each}}
	{{if items.length == 0}}
	<tr>
		<td colspan="11" class="none-data-tip">没有相关数据</td>
	</tr>
	{{/if}}
</script>

<script id="manageCustomerTemplate" type="text/html">
<div>
	<div class="main" id="customerListDiv">
		<div class="inquiry">
			<form id="searchForm_search">
				<input type="hidden" name="currentPage" value="1">
				<input type="hidden" name="toolStyle" value="pms">
				<input type="hidden" name="limit" value="10">
				<input type="hidden" name="method" value="searchCustomerPage">
				<input type="hidden" name="dealerNum" value="${dealerNum}">
				<input type="hidden" name="customerGroupId" value="{{customerGroupId}}">

				<div class="group"><label>车辆品牌：</label>
					<select name="carBrand" id="carBrand">
						<option value="">--全部--</option>
						<c:forEach items="${vehicleBrands}" var="vb">
							<option value="${vb.code}">${vb.codeValue}</option>
						</c:forEach>
					</select>
				</div>
				<div class="group"><label>手机：</label>
					<input class="" type="text" name="mobilePhone" id="mobilePhone" value="" />
				</div>
				<div class="group"><label>车牌：</label>
					<input class="" type="text" name="carPlate" id="carPlate" value="" />
				</div>
				<div class="group"><label>一年累计进店次数：</label>
					<input class="mini" type="text" name="countOfToStoreMin" id="countOfToStoreMin" value="" />
					- <input class="mini" type="text" id="countOfToStoreMax" name="countOfToStoreMax" value="" />
				</div>
				<div class="group"><label>一年累计消费金额：</label>
					<input class="mini" type="text" name="moneyOfYearMin" id="moneyOfYearMin" value="" />
					- <input class="mini" type="text" id="moneyOfYearMax" name="moneyOfYearMax" value="" /></div>
				<div class="btns"><button type="button" class="bottleGreen vm" onclick="searchCustomerPage(1)">查询</button></div>
			</form>
		</div>
		<div class="table">
			<table width="100%">
				<thead>
				<tr>
					<th width="40"><input type="checkbox" name="name" onclick="selectAll(this, 'checkSRID')" /></th>
					<th width="120">客户</th>
					<th width="80">手机号码</th>
					<th width="60">车牌号</th>
					<th width="60">车品牌</th>
					<th width="">最近一年到店次数</th>
					<th width="">最近一年消费金额</th>
					<th width="80">上次保养时间</th>
					<th width="">上次保养金额</th>
					<th width="">上次保养里程</th>
					<th width="">上次保养项目</th>
				</tr>
				</thead>
				<tbody id="detailTbody_search" class="detailTr"></tbody>
			</table>
		</div>

		<div class="pageTool" id="pageTool_search"></div>

		<div class="btns tl tc">
			<button class="green " onclick="addSelected()">添加当前选择客户</button>
			<button class="green " onclick="addAll()">添加所有符合条件的客户</button>
		</div>
		<div class="mb10"></div>
	</div>
</div>

</script>




<script id="detailTbodyTemplate_search" type="text/html">
	{{each items as v i}}
	<tr id="{{v.id}}" >
		<td><input type="checkbox" name="checkSRID" value="{{v.customerId}}" /></td>
		<td>{{v.memberName}}</td>
		<td>{{v.mobilePhone}}</td>
		<td>{{separatorValue v.carPlate}}</td>
		<td>{{separatorValue v.carBrand}}</td>
		<td>{{v.countOfToStore}}</td>
		<td>{{v.moneyOfYear}}</td>
		<td>{{v.lastMaintenanceDate}}</td>
		<td>{{v.lastMaintenanceMoney}}</td>
		<td>{{separatorValue v.lastMaintenanceMileage}}</td>
		<td>{{v.lastMaintenanceItemDisplay}}</td>
	</tr>
	{{/each}}
	{{if items.length == 0}}
	<tr>
		<td colspan="11" class="none-data-tip">没有相关数据</td>
	</tr>
	{{/if}}
</script>

<script>
	function returnPath(returnPage,send,remindMonth) {
		if(returnPage == 'remind') {
			location ='<c:url value="/remind/service/manage/${dealerNum}?send='+send+'&remindMonth='+remindMonth+'" />'
		} else if(returnPage == 'announcementSend') {
			location ='<c:url value="/announcement/send/${dealerNum}" />';
		}
	}

	function changeGroup(groupId, groupName, isCustom){
		if(g_groupId != groupId){
			g_groupId = groupId;

			$("#customerGroupId").val(groupId);
			$("#customerDetailBox").html(groupName + "");

			if(isCustom){
				$("#addCustomerToGroupBtn").show();
			}else{
				$("#addCustomerToGroupBtn").hide();
			}

			toCustomerPage(1);
		}

	}

	function toCustomerPage(page, limit) {

		var $searchForm = $("#" + searchFormID + "_customer");
		if(page) {
			$searchForm.find("input[name=currentPage]").val(page);
		}

		if(limit) {
			$searchForm.find("input[name=limit]").val(limit);
		}
		var loadIndex = ns.load("数据加载中...");


		$.ajax({
			type: "POST",
			url: "<c:url value="/customerGroup/customer/list" />",
			dataType: "json",
			data: $searchForm.serialize(),
			async: true,
			success: function (data) {
				ns.close(loadIndex);
				if (data.success) {
					var html = template(detailTbodyTemplateID + "_customer", data.data);

					$("#" + detailTbodyID + "_customer").html(html);
					$("#" + pageToolID + "_customer").html(data.data.pageToolHtml);
				} else {
					ns.error(data.message);
				}

			},
			error: function () {
				ns.close(loadIndex);
				ns.error('数据加载失败！');
			}
		});
	}

	function delCustomer(dealerNum, customerId, groupId){
		var layerIndex = layer.confirm('数据删除后将不可恢复，确定删除？', {
			icon: 3,
			title:'提示',
			btn: ['确认', '取消']
		}, function () {
			ns.close(layerIndex);
			layerIndex = ns.load("正在保存数据.....");
			$.ajax({
				type: 'POST',
				url: "<c:url value="/customerGroup/customer/del" />",
				cache: false,
				data: {
					"dealerNum": '${dealerNum}',
					"customerId": customerId,
					"groupId": groupId
				},
				error: function () {
					ns.error('操作失败');
				},
				success: function (data) {
					if (data.success) {
						ns.ok('操作成功', function () {
							toCustomerPage();
						});
					} else {
						ns.error('操作失败：' + data.message);
					}
				}
			});
		});
	}


	function addCustomer(){
		if(!g_groupId){
			ns.error("请先在左侧客户分类中选择需要添加客户的分类");
			return;
		}

		layer.open({
			type: 1,
			title: '添加客户至分组',
			area: '1000px',
			offset: '30px',
			shadeClose: true,
			content: template("manageCustomerTemplate", {customerGroupId: g_groupId}),
			success:function(){
				//loadHistory(1, 10);
				toPage(1);
			},
			end: function(){
				toCustomerPage();
			}
		});
	}


	function searchCustomerPage(page, limit) {

		var $searchForm = $("#" + searchFormID + "_search");
		if(page) {
			$searchForm.find("input[name=currentPage]").val(page);
		}

		if(limit) {
			$searchForm.find("input[name=limit]").val(limit);
		}
		var loadIndex = ns.load("数据加载中...");


		$.ajax({
			type: "POST",
			url: "<c:url value="/customerGroup/customer/addList" />",
			dataType: "json",
			data: $searchForm.serialize(),
			async: true,
			success: function (data) {
				ns.close(loadIndex);
				if (data.success) {
					var html = template(detailTbodyTemplateID + "_search", data.data);

					$("#" + detailTbodyID + "_search").html(html);
					$("#" + pageToolID + "_search").html(data.data.pageToolHtml);
					$("#customerListDiv").css("height","560px");
				} else {
					ns.error(data.message);
				}

			},
			error: function () {
				ns.close(loadIndex);
				ns.error('数据加载失败！');
			}
		});
	}


	function addAll(){
		var id = $("#customerPromotionId").val();

		var nsIndex = ns.load("正在处理数据，请稍等...");

		var data  = {
			dealerNum: '${dealerNum}',
			groupId: g_groupId,

			customerGroupId: g_groupId,
			carBrand: $("#carBrand").val(),
			countOfToStoreMin: $("#countOfToStoreMin").val(),
			countOfToStoreMax: $("#countOfToStoreMax").val(),
			moneyOfYearMin: $("#moneyOfYearMin").val(),
			moneyOfYearMax: $("#moneyOfYearMax").val()

		};

		$.ajax({
			type: "POST",
			url: '<c:url value="/customerGroup/customer/addAll" />',
			data: data,
			dataType: "json",
			async: true,
			cache:false,
			success: function(data){
				ns.close(nsIndex);
				if (data.success) {
					ns.ok("操作成功");
				} else {
					ns.error(data.message);
				}

			},
			error: function(){
				ns.close(nsIndex);
				ns.error("操作失败，请重试！");
			}
		});
	}

	function addSelected(){

		var selectSRIdArray = new Array();

		$("input[type=checkbox][name='checkSRID']:checked").each(function() {
			selectSRIdArray.push($(this).val());
		});

		if(selectSRIdArray.length < 1){
			ns.error("请先选择要添加的客户");
			return;
		}

		var data  = {
			dealerNum: '${dealerNum}',
			groupId: g_groupId,

			customerId : selectSRIdArray

		};

		var nsIndex = ns.load("正在处理数据，请稍等...");

		$.ajax({
			type: "POST",
			url: '<c:url value="/customerGroup/customer/addSelected" />',
			data: data,
			dataType: "json",
			async: true,
			cache:false,
			traditional :true,
			success: function(data){
				ns.close(nsIndex);
				if (data.success) {
					ns.ok("操作成功!");
				} else {
					ns.error(data.message);
				}

			},
			error: function(){
				ns.close(nsIndex);
				ns.error("操作失败，请重试！");
			}
		});
	}

	function add(){
	    var contentHtml = template(editTemplateID, {});

	    layer.open({
	        type: 1,
	        title: "新增",
	        area: '600px',
	        btn: ['保 存', '取 消'],
	        content: contentHtml,
	        yes: function (index, layero) {
	            var layerIndex = ns.load();
	            $.ajax({
	                type: "POST",
	                url: saveUrl,
	                dataType: "json",
	                data: $("#" + editFormID).serialize(),
	                success: function (data) {
	                    ns.close(layerIndex);
	                    if (data.success) {
	                        ns.ok('操作成功!', function () {
	                            ns.closeAll();
	                            g_groupId = data.data.id;
		                        addCustomer(g_groupId);
	                        });
	                    } else {
	                        ns.error('提交失败' + data.message);
	                    }
	                },
	                error: function () {
	                    ns.close(layerIndex);
	                    ns.error('提交失败！');
	                }
	            });
	        }, cancel: function (index) {
	            ns.closeAll();
	        }
	    });

	    $("input[type=checkbox]").change(function(){
	       $(this).prev().val($(this).prop("checked"));
	    });
	}
</script>
</body>
</html>




